package com.systar.activity.parse;

import java.util.EnumSet;

import com.google.common.eventbus.EventBus;
import com.systar.activity.state.FileActivity;
import com.systar.utils.StringLexer;

public class SessionFileParserLexer extends SessionFileParser
{
	public enum DSPrjLexem implements StringLexer.Lexem
	{
		EVENT("<", "event", "*", "kind", "="), MODULE("<", "module", "*", "priority", "="), MSG("<", "message", ">"), ;

		private String[] tokens;
		private boolean floating;

		private DSPrjLexem(String... tokens)
		{
			this(false, tokens);
		}

		private DSPrjLexem(boolean floating, String... tokens)
		{
			this.tokens = tokens;
			this.floating = floating;
		}

		@Override
		public String[] getTokens()
		{
			return tokens;
		}

		@Override
		public boolean isFloatingToken()
		{
			return floating;
		}
	}

	private class XSessionHandler implements StringLexer.LexemHandler
	{
		private StringLexer lexer;
		private String currentEventKind;
		private String currentModulePriority;

		XSessionHandler()
		{
			currentEventKind = null;
			currentModulePriority = null;
		}

		@Override
		public void setLexer(StringLexer lexer)
		{
			this.lexer = lexer;
		}

		@Override
		public void onFinish()
		{
			flush();
		}

		@Override
		public EnumSet<? extends StringLexer.Lexem> getLexems()
		{
			return EnumSet.allOf(DSPrjLexem.class);
		}

		@Override
		public void match(Enum<? extends StringLexer.Lexem> lexEnum, int position)
		{
			DSPrjLexem lexem = (DSPrjLexem) lexEnum;

			switch (lexem)
			{
			case EVENT:
			{
				currentEventKind = lexer.getString(position + 1);
			}
				break;
			case MODULE:
			{
				currentModulePriority = lexer.getString(position + 1);
			}
				break;
			case MSG:
			{
				StringBuilder message = new StringBuilder();
				for (int i = position + 1; true; i++)
				{
					String msgPart = lexer.getString(i);
					if ((msgPart == null) || "<".equals(msgPart))
						break;
					message.append(msgPart);
					message.append(" ");
				}
				submit(currentEventKind, currentModulePriority, message.toString());
			}
				break;
			}
		}
	}

	public SessionFileParserLexer(FileActivity activity, EventBus eventBus)
	{
		super(activity, eventBus);
	}

	@Override
	public Integer call() throws Exception
	{
		nbInfo = nbWarn = nbErr = 0;

		StringLexer lexer = new StringLexer(new XSessionHandler());
		lexer.parse(activity.getReader());
		return 0;
	}

}
